package com.liang.gulimall.seckill.scheduled;

import com.liang.gulimall.seckill.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架
 *  每天晚上点，上 架最近三天需要秒杀的商品。
 */
@Service
@Slf4j
public class SecKillSkuService {
    private final String upload_lock="seckill:upload:lock";
    @Autowired
    SecKillService secKillService;
    @Autowired
    RedissonClient redissonClient;
    //TODO 处理幂等和分布式
    @Scheduled(cron = "*/10 * * * * ?")
    public void uploadSecKillSkuWith3Day(){
        //忽略重复上架
        log.info("上架秒杀商品信息");
        //分布式锁
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try{
            secKillService.uploadSecKillSkuWith3Day();
        }catch (Exception e){
            log.error("上架秒杀失败，重试");
        }finally {
            lock.unlock();
        }

    }
}
